import { login, sysProfile, sysUser } from '@/api/user.js'
import { getToken, setToken } from '@/utils/auth.js'

const state = {
  token: getToken() || '',
  userInfo: ''
}

const mutations = {
  updateToken (state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo (state, value) {
    state.userInfo = value
  },
  // 退出登录
  logout () {
    state.token = ''
    setToken('')
  }
}

const actions = {
  // 登录调用
  async toLogin ({ commit }, value) {
    const res = await login(value)
    commit('updateToken', res.data)
  },
  // 获取用户个人信息
  async getUserInfo ({ commit }) {
    // 获取员工部分信息，不包括头像等信息
    const res = await sysProfile()
    // 通过userId获取其他信息
    const res2 = await sysUser(res.data.userId)
    commit('setUserInfo', {...res.data, ...res2.data})
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
